<template>
  <div>
    <div class="header">
      <input type="file" @change="handleChange" />
    </div>
    <div class="container" ref="container"></div>
  </div>
</template>

<script setup>
import jsPreviewExcel from "@js-preview/excel";
import "@js-preview/excel/lib/index.css";
import axios from "axios";

const container = ref();

async function handleChange(e) {
  const file = e.target.files[0];
  const blob = await fileToBlob(file);
  const url = blobToUrl(blob);
  preview(url);
}

function blobToUrl(blob) {
  return window.URL.createObjectURL(blob);
}

function fileToBlob(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsArrayBuffer(file);
    let blob = null;
    reader.onload = (e) => {
      if (typeof e.target.result === "object") {
        blob = new Blob([e.target.result]);
      } else {
        blob = e.target.result;
      }
      resolve(blob);
    };
  });
}

async function getDoc() {
  const res = await axios({
    url: "http://localhost:8000/order.xlsx",
    method: "get",
    responseType: "blob",
  });
  const blob = res.data;
  const url = blobToUrl(blob);
  preview(url);
  // window.open("http://localhost:8000/1.pdf");
}

getDoc();

function preview(url) {
  const excelPreviewer = jsPreviewExcel.init(container.value);
  excelPreviewer.preview(url);
}
</script>

<style scoped lang="scss">
.header {
  position: fixed;
  left: 20px;
  top: 20px;
}

.container {
  width: 100%;
  height: 100vh;
}
</style>
